﻿namespace VisualSVN.Core.Licensing
{
    using System;

    public class PlainLicenseSerializer
    {
        private static int dayIndex = 4;
        private const int EvaluationPeriod = 30;
        private static int monthIndex = 0x12;
        private const int xxx = 10;
        private static int yearIndex = 10;

        public License Deserialize(string key)
        {
            License license = new License();
            license.StartTime = ParsePlainDate(key);
            license.EndTime = license.StartTime.AddDays(30.0);
            license.Type = LicenseType.Evaluation;
            license.LicensedTo = "Evaluation User";
            license.IsPregenerated = true;
            license.Capacity = 1;
            license.Binding = LicenseBinding.Seat;
            return license;
        }

        private static DateTime ParsePlainDate(string plainKey)
        {
            DateTime time;
            try
            {
                if (plainKey.Length < 10)
                {
                    throw new LicensingException("Cannot parse license date.");
                }
                string str = "";
                for (int i = 0; i < plainKey.Length; i++)
                {
                    str = str + ((char) (plainKey[i] - '\n'));
                }
                int day = int.Parse(str.Substring(dayIndex, 2));
                int month = int.Parse(str.Substring(monthIndex, 2));
                time = new DateTime(int.Parse(str.Substring(yearIndex, 4)), month, day);
            }
            catch (FormatException exception)
            {
                throw new LicensingException("Cannot parse license date. Date format is invalid.", exception);
            }
            catch (OverflowException exception2)
            {
                throw new LicensingException("Cannot parse license date. Date is not in correct range.", exception2);
            }
            return time;
        }
    }
}

